﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Tb.App.API.Applications.Command.UploadImage;
using Tb.App.Domain;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.UploadImage
{
    /// <summary>
    /// 上传多张图片命令
    /// </summary>
    public class UploadBatchImageCommandHandler : IRequestHandler<UploadBatchImageCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Images> imagesRep;
        private readonly IWebHostEnvironment web;

        public UploadBatchImageCommandHandler(IBaseRepository<Images> imagesRep,
            IWebHostEnvironment web)
        {
            this.imagesRep = imagesRep;
            this.web = web;
        }
        public async Task<ApiResult<int>> Handle(UploadBatchImageCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            // 保存图片到服务器
            var uploadDir = Path.Combine(web.WebRootPath, "uploads");
            if (!Directory.Exists(uploadDir))
                Directory.CreateDirectory(uploadDir);

            // 生成唯一文件名（避免重复）
            var fileName = $"{Guid.NewGuid()}{Path.GetExtension(request.ImageFile.FileName)}";
            var savePath = Path.Combine(uploadDir, fileName);

            using (var stream = new FileStream(savePath, FileMode.Create))
            {
                await request.ImageFile.CopyToAsync(stream, cancellationToken);
            }

            var image = new Images
            {
                BatchNo = request.BatchNo,
                ImageType = request.ImageType,
                ImagePath = $"http://localhost:5198/uploads/{fileName}",
            };
            await imagesRep.AddAsync(image);
            result.Code = ApiEnum.添加成功;
            result.Message = "图片上传成功";
            result.Data = image.Id;

            return result;
        }
    
    }
}
